#include "socket_connector.h"

#include <arpa/inet.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstring>

#include "logger.h"
#include "socket_connection.h"

int SocketConnector::SetAddress(const std::string &address)
{
    address_ = address;
    return 0;
}

int SocketConnector::SetPort(int port)
{
    port_ = port;
    return 0;
}

std::shared_ptr<SocketConnection> SocketConnector::Connect()
{
    auto fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(port_),
        .sin_addr = {
            .s_addr = inet_addr(address_.c_str())
        },
    };
    auto ret = connect(fd,
                       reinterpret_cast<struct sockaddr *>(&addr),
                       sizeof(struct sockaddr));
    if (ret) {
        LOGGER() << "connect failed: " << strerror(errno) << std::endl;
        return nullptr;
    }

    return std::make_shared<SocketConnection>(fd);
}
